﻿using System.IO;

namespace Microsoft.Azure.E2E.Common.Net
{
    /// <summary>
    /// A part of a <see cref="MultipartMessage"/> that contains a stream
    /// </summary>
    public class StreamPart : MessagePart
    {
        private readonly Stream _value;
        private readonly string _fileName;
        private readonly string _contentType;

        /// <summary>
        /// Creates a new <see cref="StreamPart"/>, representing a file in a <see cref="MultipartMessage"/>
        /// </summary>
        /// <param name="fileName">The name to give the file in the message</param>
        /// <param name="value">A stream containing the data that should be included in the message</param>
        /// <param name="contentType">The content type of the <paramref name="value"/></param>
        public StreamPart(string fileName, Stream value, string contentType)
        {
            _fileName = fileName;
            _value = value;
            _contentType = contentType;
        }

        /// <summary>
        /// Gets the name that will be associated to the stream in the resulting <see cref="MultipartMessage"/>
        /// </summary>
        public string FileName { get { return _fileName; } }

        /// <summary>
        /// Gets whatever value must follow the name attribute on the part separator, return null if nothing is required
        /// </summary>
        protected override string NameTail
        {
            get { return string.Format("filename=\"{1}\"{0}Content-Type: {2}", "\r\n", _fileName, _contentType); }
        }

        /// <summary>
        /// Gets the name of the part
        /// </summary>
        public override string Name
        {
            get { return "file"; }
        }

        /// <summary>
        /// Gets the content type that has been associated with the value
        /// </summary>
        public string ContentType
        {
            get { return _contentType; }
        }

        /// <summary>
        /// Gets the content disposition header value for the part
        /// </summary>
        public override string ContentDisposition
        {
            get { return "form-data"; }
        }

        /// <summary>
        /// Gets a stream representing the value contained in the part
        /// </summary>
        /// <returns>A stream representing the value contained in the part</returns>
        protected override Stream GetDataStream()
        {
            return _value;
        }

        /// <summary>
        /// Frees any resources used by the part
        /// </summary>
        public override void Dispose()
        {
            _value.Dispose();
        }
    }
}